#include"yuechuan.h"
#include"iomanager.h"
#include<sys/socket.h>
#include<fcntl.h>
#include<netinet/in.h>
#include<unistd.h>
#include<arpa/inet.h>

yuechuan::Logger::ptr g_logger = YUECHUAN_LOG_NAME("root");

void test_fiber() {
    YUECHUAN_LOG_INFO(g_logger) << "test_fiber";
}

void test1() {

    int socketFd = socket(AF_INET, SOCK_STREAM, 0);
    fcntl(socketFd, F_SETFL, O_NONBLOCK);
    sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(80);
    inet_pton(AF_INET, "14.119.104.254", &serverAddr.sin_addr.s_addr);
    if (!connect(socketFd, (const sockaddr *) &serverAddr, sizeof(serverAddr))) {
    } else if (errno == EINPROGRESS) {
        YUECHUAN_LOG_INFO(g_logger) << "add Event Error " << errno << " : " << strerror(errno);
        yuechuan::IOManager::GetThis()->addEvent(socketFd, yuechuan::IOManager::READ, []() {
            YUECHUAN_LOG_INFO(g_logger) << " Read Connect ";
        });
        yuechuan::IOManager::GetThis()->addEvent(socketFd, yuechuan::IOManager::WRITE, [&]() {
            YUECHUAN_LOG_INFO(g_logger) << " Write Connect ";
            yuechuan::IOManager::GetThis()->cancelEvent(socketFd, yuechuan::IOManager::READ);
            close(socketFd);
        });
    }
}
yuechuan::Timer::ptr s_timer;
void test_timer(){
    yuechuan::IOManager iom(2);
    s_timer = iom.addTimer(500, [](){
        static int i = 0;
        YUECHUAN_LOG_INFO(g_logger) << " i = " << i;

        if(++i == 5){
//            s_timer->cancel();
            s_timer->reset(1000, true);
        }
    }, true);
}

int main(int argv, char **argc) {
//    yuechuan::IOManager iom(2, false);
//    iom.schedule(&test1);
//    test1();
    test_timer();
    return 0;
}
